import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Like, Repository } from 'typeorm';
import GatherInterfaceImage from '@main/entities/service/admin/gather/gather-interface-image.entity';
import { ApiException } from '@main/common/exceptions/api.exception';
import { app } from 'electron';
import path from 'path';
import * as fs from 'fs';
import { SysOperationLogService } from '../../system/operationLog/operationLog.service';

@Injectable()
export class GatherInterfaceImageService {
  constructor(
    @InjectRepository(GatherInterfaceImage)
    private interfaceImageRepository: Repository<GatherInterfaceImage>,
    private operationLogService: SysOperationLogService,
  ) {}

  async list() {
    return await this.interfaceImageRepository.find();
  }

  /**
   * 罗列所有配置
   */
  async page(data) {
    const { pageSize, pageNum, entity = {} } = data;

    const { imgName, imgCode } = entity;

    return await this.interfaceImageRepository.findAndCount({
      where: {
        imgName: Like(`%${imgName}%`),
        imgCode: Like(`%${imgCode}%`),
      },
      order: {
        updateTime: 'DESC',
      },
      take: pageSize,
      skip: (pageNum - 1) * pageSize,
    });
  }

  /**
   * 新增
   */
  async add(data, user, mac, ip, syncHostSqlite) {
    const databaseOperationLogList = [];
    const interfaceImage = await this.interfaceImageRepository.insert({
      ...data,
      createName: user.nickName,
      createUserName: user.userName,
      updateName: user.nickName,
      updateUserName: user.userName,
    });
    databaseOperationLogList.push({
      type: 'add',
      dataType: 'obj',
      database: 'GatherInterfaceImage',
      checkOnlyKeyList: [],
      data: interfaceImage,
      whereObj: null,
      remark: `GatherInterfaceImage表新增数据`,
    });
    await this.operationLogService.add(
      {
        type: 'add',
        msg: `调机图片管理模块新增调机图片`,
        databaseOperationLogList,
        remark: `新增调机图片${data.imgName}`,
        mac,
        ip,
        syncHostSqlite: isNaN(Number(syncHostSqlite)) ? 0 : Number(syncHostSqlite),
      },
      user
    );
  }

  /**
   * 更新
   */
  async update(data, user, mac, ip, syncHostSqlite) {
    const databaseOperationLogList = [];

    const { id, remark, imgName, imgUrl } = data;

    await this.interfaceImageRepository.update(
      { id },
      { imgName, imgUrl, remark, updateName: user.nickName, updateUserName: user.userName }
    );

    databaseOperationLogList.push({
      type: 'update',
      dataType: 'obj',
      database: 'GatherInterfaceImage',
      checkOnlyKeyList: [],
      data: { remark, updateName: user.nickName, updateUserName: user.userName },
      whereObj: { id },
      remark: `GatherInterfaceImage表更新调机图片`,
    });
    await this.operationLogService.add(
      {
        type: 'update',
        msg: `调机图片管理模块更新调机图片`,
        databaseOperationLogList,
        remark: `更新调机图片${data.imgName}`,
        mac,
        ip,
        syncHostSqlite: isNaN(Number(syncHostSqlite)) ? 0 : Number(syncHostSqlite),
      },
      user
    );
  }

  /**
   * 删除
   */
  async delete(idList, user, mac, ip, syncHostSqlite) {
    const databaseOperationLogList = [];
    const result = await this.interfaceImageRepository.findOne({ where: { id: idList } });
    console.log('图片文件', result);
    const destinationPath = app.getPath('userData') + '/UploadFile';
    // 拼接目标文件路径
    const imagePath = path.join(destinationPath, result.imgUrl);

    fs.unlink(imagePath, (err) => {
      if (err) {
        console.error(err);
        return;
      }
      console.log('图片文件已成功删除');
    });

    await this.interfaceImageRepository.delete(idList);
    databaseOperationLogList.push({
      type: 'delete',
      dataType: 'array',
      database: 'GatherInterfaceImage',
      checkOnlyKeyList: [],
      data: null,
      whereObj: idList,
      remark: `GatherInterfaceImage表删除调机图片`,
    });
    await this.operationLogService.add(
      {
        type: 'delete',
        msg: `调机图片管理模块删除调机图片`,
        databaseOperationLogList,
        remark: `删除调机图片`,
        mac,
        ip,
        syncHostSqlite: isNaN(Number(syncHostSqlite)) ? 0 : Number(syncHostSqlite),
      },
      user
    );
  }

  async isExistKey(data) {
    const { imgCode } = data;

    const result = await this.interfaceImageRepository.findOne({ where: { imgCode } });

    if (result) {
      throw new ApiException(10040);
    }
  }
}
